package com.cgycms.prototype.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cgycms.prototype.ProjectManagerService;
import com.cgycms.prototype.common.BaseController;
import com.cgycms.prototype.common.BizException;
import com.cgycms.prototype.common.Result;
import com.cgycms.prototype.entity.PrototypeFileEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * @author: 超哥呦
 * @Description: 原型功能控制器
 * @date: 2021/11/18 20:20
 **/
@Api(tags = "原型文件上传模块")
@RestController
@RequestMapping("/projectManager")
public class ProjectManagerController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProjectManagerService projectManagerService;


    /**
     * 上传原型接口 ，不支持压缩包多级目录。
     *
     * @param multipartFile file压缩包对象
     * @param code          项目编码
     * @return
     */
    @ApiOperation(value = "上传原型压缩文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件对象", name = "file", dataType = "MultipartFile", required = true),
            @ApiImplicitParam(value = "项目编码", name = "code", dataType = "String", required = true),
            @ApiImplicitParam(value = "项目ID", name = "projectId", dataType = "Long", required = true)
    })
    @PostMapping("/projectUpload")
    public Result projectUpload(@RequestParam("file") MultipartFile multipartFile, @RequestParam("code") String code,@RequestParam("projectId") Long  projectId) {
        if (ObjectUtil.isEmpty(code)) {
            return error("项目编号不能为空！");
        }
        if (multipartFile == null || multipartFile.isEmpty() || StrUtil.isEmpty(multipartFile.getOriginalFilename())) {
            return error("文件不能为空！");
        }
        try {
            return success(projectManagerService.projectUpload(code,projectId, multipartFile));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传出错了。{}" + e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 下载原型文件
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "下载原型文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键ID", name = "id", dataType = "Long", required = true)
    })
    @GetMapping("/projectDownload")
    public void projectDownload(@RequestParam Long id, HttpServletResponse response) {
        if (ObjectUtil.isEmpty(id)) {
            throw new BizException("必填参数为空!");
        }
        PrototypeFileEntity entity = projectManagerService.getById(id);
        if (ObjectUtil.isNull(entity)) {
            throw new BizException("没有找到原型文件请刷新再试!");
        }
        OutputStream outputStream = null;
        try {
            File dataFile = FileUtil.file(entity.getDiskPath());
            InputStream fis = FileUtil.getInputStream(entity.getDiskPath());
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(entity.getOriginalName(), "UTF-8"));
            response.addHeader("Content-Length", "" + dataFile.length());
            outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("{}:下载原型文件出错!", id);
        } finally {
            IoUtil.close(outputStream);
        }
    }

    /**
     * 删除原型文件
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除原型文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键ID", name = "id", dataType = "Long", required = true)
    })
    @GetMapping("/projectDelete")
    public Result projectDelete(@RequestParam Long id) {
        if (ObjectUtil.isEmpty(id)) {
            return error("参数不能为空！");
        }
        return success(projectManagerService.projectDelete(id));
    }

}
